package net.prasenjit.poc.httpclient;

import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.conn.SchemeRegistryFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * Created by PPurohit on 12/22/2014.
 */
public class SchemeRegistryFactoryBean implements FactoryBean<SchemeRegistry>, InitializingBean {

    private TrustStrategy trustStrategy;

    private X509HostnameVerifier hostnameVerifier;

    private SchemeRegistry schemeRegistry;

    @Override
    public SchemeRegistry getObject() throws Exception {
        return schemeRegistry;
    }

    @Override
    public Class<?> getObjectType() {
        return SchemeRegistry.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(trustStrategy);
        Assert.notNull(hostnameVerifier);

        // HTTP scheme
        schemeRegistry = SchemeRegistryFactory.createDefault();
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        schemeRegistry.register(http);

        // HTTPS scheme
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStrategy, hostnameVerifier);
        Scheme https = new Scheme("https", 443, sslSocketFactory);
        schemeRegistry.register(https);
    }

    public void setTrustStrategy(TrustStrategy trustStrategy) {
        this.trustStrategy = trustStrategy;
    }

    public void setHostnameVerifier(X509HostnameVerifier hostnameVerifier) {
        this.hostnameVerifier = hostnameVerifier;
    }
}
